from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import simplejson as json
import geohash
import datetime

def lod_2_table(lod):
    if len(lod) > 0:
        trs = []
        trs.append('<tr>%s</tr>' % '\n'.join(['<th>%s</th>' % k for k in lod[0]]))
        for i in lod:
            trs.append('<tr>%s</tr>' % '\n'.join(['<td>%s</td>' % i[k] for k in i]))
        return '<table>%s</table>' % '\n'.join(trs)
    return 'blank'

class Unit(db.Model):
    ep = db.IntegerProperty(default=10)
    sp = db.IntegerProperty(default=10)
    owner = db.StringProperty(required=True)
    loc = db.StringProperty(default='ezs42e44yx96')
    x = db.FloatProperty(default=42.6)
    y = db.FloatProperty(default=-5.6)
    updated = db.DateTimeProperty(auto_now=True)
    type = db.StringProperty(default='base')
    
    def to_dict(self):
        return {'ep':self.ep,
                'sp':self.sp,
                'x':self.x,
                'y':self.y,
                'loc':self.loc,
                'type':self.type,
                'owner':self.owner,
                'updated':self.updated.strftime("%Y-%m-%d %H:%M:%S"),
                'key':str(self.key())}
        
    def regen(self):
        t1 = self.updated
        t2 = datetime.datetime.utcnow()
        d = t2 - t1
        self.ep += d.seconds
        if self.ep > 20:
            self.ep = 20
                
class attack(webapp.RequestHandler):
    def get(self,atk,tgt):
        atk = get_item(atk)
        atk.regen()
        atk.ep -= 10
        
        tgt = get_item(tgt)
        tgt.regen()
        tgt.sp -= 1
        
        db.put([atk,tgt])
        
        res = lod_2_table([atk.to_dict(),tgt.to_dict()])
        self.response.out.write(res)
        
class scan(webapp.RequestHandler):
    def get(self,key,x1,y1,x2,y2):
        ll = str(geohash.Geohash((float(x1), float(y1))))
        ur = str(geohash.Geohash((float(x2), float(y2))))
        
        unit = get_item(key)
        unit.regen()
        unit.ep -= 15
        unit.put()

        q = Unit.all()
        q.filter('loc <', ur)
        q.filter('loc >', ll)
        units = q.fetch(100)

        res = lod_2_table([u.to_dict() for u in units])
        self.response.out.write(res)
        
class create(webapp.RequestHandler):
    def get(self,owner,type,x,y):
        x=float(x)
        y=float(y)
        loc = str(geohash.Geohash((x, y)))
        unit = Unit(owner=owner,x=x,y=y,loc=loc)
        unit.put()
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('added')
        
class move(webapp.RequestHandler):
    def get(self,key,x,y):
        x=float(x)
        y=float(y)
        loc = str(geohash.Geohash((x, y)))
        
        unit = get_item(key)
        unit.regen()
        unit.x = x
        unit.y = y
        unit.loc = loc
        unit.ep -= 20
        unit.put()
        
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('moved')
        
class dump(webapp.RequestHandler):
    def get(self):
        db.delete(Unit.all())
    
class unit_handler(webapp.RequestHandler):
    def get(self,owner):
        units = db.GqlQuery("SELECT * FROM Unit WHERE owner = :1",owner)
        j = lod_2_table([u.to_dict() for u in units])
        self.response.out.write(j)
        
    def post(self):
        ep = int(self.request.get("ep"))
        owner = self.request.get("owner")

        unit = Unit(owner=owner,ep=ep)
        unit.put()
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('added')


class main_page(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')


app = webapp.WSGIApplication([('/', main_page),
                              (r'/unit/(.*)', unit_handler),
                              (r'/unit', unit_handler),
                              (r'/attack/(.*)/(.*)', attack),
                              (r'/move/(.*)/(.*)/(.*)', move),
                              (r'/create/(.*)/(.*)/(.*)/(.*)', create),
                              (r'/scan/(.*)/(.*)/(.*)/(.*)/(.*)', scan),
                              (r'/db/dump', dump)
                              ], debug=True)

def get_item(key):
    return db.get(db.Key(key))

def main():
    run_wsgi_app(app)

if __name__ == "__main__":
    main()
